const Log = require('../models/Log');

class LogService {
  /**
   * 记录用户操作日志
   * @param {Object} params 日志参数
   * @param {string} params.userId 用户ID
   * @param {string} params.action 操作类型
   * @param {string} params.ip IP地址
   * @param {string} params.userAgent 用户代理
   * @param {Object} [params.details] 额外详情
   */
  static async createLog({ userId, action, ip, userAgent, details = {} }) {
    try {
      const log = new Log({
        userId,
        action,
        ip,
        userAgent,
        details
      });
      await log.save();
      return log;
    } catch (error) {
      console.error('[日志记录失败]', error);
      throw error;
    }
  }

  /**
   * 获取用户操作日志
   * @param {string} userId 用户ID
   * @param {Object} options 查询选项
   * @param {number} [options.page=1] 页码
   * @param {number} [options.limit=20] 每页数量
   * @param {string} [options.action] 操作类型过滤
   * @param {Date} [options.startDate] 开始日期
   * @param {Date} [options.endDate] 结束日期
   */
  static async getUserLogs(userId, options = {}) {
    const {
      page = 1,
      limit = 20,
      action,
      startDate,
      endDate
    } = options;

    const query = { userId };

    if (action) {
      query.action = action;
    }

    if (startDate || endDate) {
      query.timestamp = {};
      if (startDate) query.timestamp.$gte = startDate;
      if (endDate) query.timestamp.$lte = endDate;
    }

    try {
      const [logs, total] = await Promise.all([
        Log.find(query)
          .sort({ timestamp: -1 })
          .skip((page - 1) * limit)
          .limit(limit)
          .populate('userId', 'username email'),
        Log.countDocuments(query)
      ]);

      return {
        logs,
        pagination: {
          total,
          page,
          limit,
          pages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      console.error('[获取用户日志失败]', error);
      throw error;
    }
  }

  /**
   * 清理过期日志
   * @param {number} days 保留天数
   */
  static async cleanOldLogs(days = 90) {
    const date = new Date();
    date.setDate(date.getDate() - days);

    try {
      const result = await Log.deleteMany({
        timestamp: { $lt: date }
      });
      return result;
    } catch (error) {
      console.error('[清理过期日志失败]', error);
      throw error;
    }
  }
}

module.exports = LogService; 